package com.shixun.milktea.handler;



import com.shixun.milktea.entity.Consumer;
import com.shixun.milktea.entity.Manager;
import com.shixun.milktea.utils.JwtUtil;
import com.shixun.milktea.utils.RedisUtil;
import com.shixun.milktea.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class UserAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private JwtUtil jwtUtil;
    /**
     * 登录成功后处理
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //从身份证中获取用户信息

        Manager manager = (Manager) authentication.getPrincipal();
//        Consumer consumer = (Consumer) authentication.getPrincipal();
        System.out.println(manager);


        ResultVO resultVO = new ResultVO(manager);
        resultVO.out(response);

//        if (consumer!=null){
//            ResultVO resultVO = new ResultVO(consumer);
//            resultVO.out(response);
//        }

//        //把用户信息存入 安全上下文中
//        SecurityContextHolder.getContext().setAuthentication(authentication);
//        redisUtil.save(manager.getManagerId(),authentication);//将用户身份保存到redis
//        //生成token
//        String token = jwtUtil.generateToken(manager.getManagerId());
//        System.out.println(token);
//        //保存到redis
//        redisUtil.save(manager.getManagerId(),token);
//
//        //写响应头
//        response.setHeader("token",token);
//        //解决办法就是加上这一行代码，跨域访问允许访问的响应头的内容
//        response.setHeader("Access-Control-Expose-Headers","token");
        //返回当前登录用户的信息
//        ResultVO resultVO = new ResultVO(manager);

    }

}
